import React, { useEffect, useMemo, useState } from 'react';
import { ILoadMapTypeAll } from '@/common';
import { useDescriptionsType } from '@/components/DescriptionsType';
import { DatePicker, Form, Input, Select, Tooltip, TreeSelect, message, Button } from 'antd';
import { UploadFormCommon } from '@/components/UploadForm';
import { UpdateAssetView } from './UpdateAssetView';
import { downloadTemplate, getFileNameNotType, getTenantID, splitFileUrl } from '@/utils';
import MyIcon from '@/components/MyIcon';
import moment from 'moment';
import { getBaseUrl } from '@/services/urlconst';
import { readReadShowFileService } from '@/services/BaseLayout';
import { EyeOutlined } from '@ant-design/icons';

const getUpdateConfig = ({ pageType, record, openAssetModalStatus }) => {
  /** 表单数据 */
  const [acceptForm] = Form.useForm();

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  /** 切换表单 */
  useEffect(() => {
    // 回填表单
    if (Object.keys(record).length !== 0) {
      acceptForm.setFieldsValue({
        ...record,
        createTime: moment(record?.createTime),
      });
    }
  }, [record]);

  const disabled: boolean = pageType === 'detail';

  /** 表单配置 */
  const [config, methods] = useDescriptionsType({
    labelWidth: 190,
    basicForm: acceptForm,
    name: 'accept-addAndEdit',
    schemas: [
      {
        key: 'accept-basic',
        title: '',
        fieldChildren: [
          {
            label: '申请日期',
            field: 'createTime',
            component: 'DatePicker',
            placeholder: '请选择申请日期',
            disabled: disabled,
            required: true,
            disabledDate: (current) => {
              return current && current > moment(new Date(), 'YYYY-MM-DD');
            },
          },
          {
            field: `applyCode`,
            label: `流水单号`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
            // required: true,
          },
          {
            field: `createrName`,
            label: `申请人`,
            component: 'Input',
            // required: true,
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `createPhone`,
            label: `联系电话`,
            component: 'Input',
            // required: true,
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `createDepartmentName`,
            label: `申请部门/单位`,
            component: 'Input',
            // required: true,
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `createPositionName`,
            label: `职务岗位`,
            component: 'Input',
            // required: true,
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `applyTitle`,
            label: `事项名称`,
            component: 'Input',
            // colSpan: record?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002` && record?.newMaintenTime ? 1 : 2,
            disabled: disabled,
            placeholder: '请输入',
            required: !disabled,
            colSpan: 0,
          },
          {
            field: `handlePerson`,
            label: `维修人`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
            required: false,
            ishidden: !(record?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002`) || !record?.newMaintenTime,
          },
          {
            field: `handleTime`,
            label: `完成时间`,
            component: 'Input',
            required: false,
            disabled: true,
            placeholder: '自动带出',
            ishidden: !(record?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002`) || !record?.newMaintenTime,
          },
          {
            field: `newMaintenTime`,
            label: `下次维保日期`,
            required: !disabled,
            component: 'Input',
            disabled: disabled,
            colSpan: 1,
            placeholder: '自动带出',
            ishidden: !(record?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002`) || !record?.newMaintenTime,
          },
          {
            field: `handleNumber`,
            label: `维修人电话`,
            component: 'Input',
            // required: true,
            placeholder: '自动带出',
            disabled: disabled,
            ishidden: !(record?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002`) || !record?.newMaintenTime,
          },
          {
            field: `spend`,
            label: `维修花费`,
            component: 'InputNumber',
            // required: true,
            placeholder: '自动带出',
            min: 0,
            disabled: disabled,
            ishidden: !(record?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002`) || !record?.newMaintenTime,
          },
          {
            field: `content`,
            label: `维修原因及内容`,
            component: 'InputTextArea',
            disabled: disabled,
            placeholder: '请输入',
            required: !disabled,
            colSpan: 2,
            allowClear: true,
            showCount: true,
            maxLength: 200,
            autoSize: { minRows: 2, maxRows: 4 },
          },
          {
            field: `applyFile`,
            label: `相关附件`,
            component: 'Render',
            disabled: disabled,
            placeholder: '请选择',
            render: (text, record) => {
              const fileName = 'applyFile';
              return (
                <>
                  {!disabled ? (
                    <UploadFormCommon
                      form={acceptForm}
                      fileFormName={fileName}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      required={false}
                      // accept={'.doc|.docx'}
                      url={'/assetInfo/uploadFile'}
                      downloadUrl={'/assetInfo/downloadFile'}
                      fileFormDelName={'delFile'}
                      delFunc={(delFilePath: string) => {
                        console.log('--- w文件url', delFilePath);
                      }}
                      // maxFile={1}
                      defaultFiles={text}
                      // hintTitle={'且只能上传 1 个！'}
                      fieldBusiPath={'assetFile'}
                    >
                      上传
                    </UploadFormCommon>
                  ) : (
                    <div
                      style={{
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        marginLeft: '8px',
                      }}
                    >
                      {record?.[fileName]
                        ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                            return (
                              <div>
                                <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                                  <a
                                    onClick={() => {
                                      message.success('下载中，请稍后...');
                                      downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                                    }}
                                  >
                                    <MyIcon type="icon-file-text-fill" />
                                    &nbsp;
                                    {getFileNameNotType(e.attachName, 8)}
                                  </a>
                                </Tooltip>
                                {/* 轻阅读预览 */}
                                <Tooltip title={'在线预览'}>
                                  <Button type="link" size="small" onClick={() => onOpenReadOfdWord(e?.attachUrl)} icon={<EyeOutlined />} />
                                </Tooltip>
                              </div>
                            );
                          })
                        : '--'}
                    </div>
                  )}
                </>
              );
            },
          },
          {
            field: `handleProve`,
            label: `回执单`,
            component: 'Render',
            disabled: false,
            placeholder: '请选择',
            ishidden: !(record?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002`) || !record?.newMaintenTime,
            render: (text, record) => {
              const fileName = 'handleProve';
              return (
                <>
                  <div
                    style={{
                      height: '100%',
                      display: 'flex',
                      alignItems: 'center',
                      marginLeft: '8px',
                    }}
                  >
                    {record?.[fileName]
                      ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                          return (
                            <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                              <a
                                onClick={() => {
                                  message.success('下载中，请稍后...');
                                  downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                                }}
                              >
                                <MyIcon type="icon-file-text-fill" />
                                &nbsp;
                                {getFileNameNotType(e.attachName, 8)}
                              </a>
                            </Tooltip>
                          );
                        })
                      : '--'}
                  </div>
                </>
              );
            },
          },
        ],
      },
      {
        key: 'accept-procurement',
        title: '',
        fieldCustomDom: <UpdateAssetView pageType={pageType} openAssetModalStatus={openAssetModalStatus} />,
      },
    ],
  });

  return {
    config,
    methods,
  };
};

export { getUpdateConfig };
